#include "./DashBoard.hpp"
#include <QPainter>
#include <QPaintEvent>
#include <QDebug>
#include <Windows.h>
#include <Pdh.h>
#include <PdhMsg.h>

DashBoardWidget::DashBoardWidget( QWidget *parent ) 
    : QWidget( parent ), cpu_usage( 0.0 ), memory_usage( 0.0 ) {
    cpu_history.fill( 0.0, 100.0 );
    memory_history.fill( 0.0, 100.0 );
    // timer 已经在头文件中定义(不是声明)
    connect( &timer, &QTimer::timeout, this, &DashBoardWidget::updateData );
    timer.start( 1000 );
}

// void DashBoardWidget::fetchSystemStats() {
//     static bool init = false;
//     static PDH_HQUERY cpuQuery;
//     static PDH_HCOUNTER cpuCounter;
//     if ( !init ) {
//         PdhOpenQuery( NULL, 0, &cpuQuery );
//         PdhAddCounter(cpuQuery, (LPCWSTR)"\\Processor(_Total)\\% Processor Time", 0, &cpuCounter);
//         init = true;
//     }
//         PdhCollectQueryData(cpuQuery);
//     PDH_FMT_COUNTERVALUE counterVal;
//     PdhGetFormattedCounterValue(cpuCounter, PDH_FMT_DOUBLE, NULL, &counterVal);
//     cpu_usage = counterVal.doubleValue;
    
    
//     // 内存：使用 GlobalMemoryStatusEx
//     MEMORYSTATUSEX statex;
//     statex.dwLength = sizeof (statex);
//     GlobalMemoryStatusEx(&statex);
//     memory_usage = (statex.ullTotalPhys - statex.ullAvailPhys) / (double)statex.ullTotalPhys * 100.0;
// }

void DashBoardWidget::paintEvent( QPaintEvent *event ) {
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint( QPainter::Antialiasing );
    int w = width(), h = height();

    // %1% 是占位符;  0: 不做填充;  'f': 浮点数格式;  2: 保留小数后两位
    QString strCPU = QString(" CPU Usage:%1% ").arg( cpu_usage, 0, 'f', 2 );
    QString strMem = QString(" Mem Usage:%1% ").arg( memory_usage, 0, 'f', 2 );
    // Draw CPU line graph
    QRect cpuRect( 10, 10, w - 20, (h-30) / 2 );
    painter.drawText( cpuRect.topLeft(), strCPU );
    painter.save();
    painter.setClipRect(cpuRect);

    QPoint prev;
    for ( int i = 0; i < cpu_history.size(); ++i ) {
        double val = cpu_history[i] / 100.0;
        int x = cpuRect.left() + i * cpuRect.width() / cpu_history.size();
        int y = cpuRect.bottom() - val * cpuRect.height();
        if ( i == 0 ) prev = QPoint( x, y );
        painter.drawLine( prev, {x, y} );
        prev = { x, y };
    }
    painter.restore();

    // Draw Mem line graph
    QRect memRect(10, cpuRect.bottom() + 20, w - 20, (h - 30) / 2);
    painter.drawText(memRect.topLeft(), strMem);
    painter.save();
    painter.setClipRect(memRect);
    for (int i = 0; i < memory_history.size(); ++i) {
        double val = memory_history[i] / 100.0;
        int x = memRect.left() + i * memRect.width() / memory_history.size();
        int y = memRect.bottom() - val * memRect.height();
        if (i == 0) prev = QPoint(x, y);
        painter.drawLine(prev, {x, y});
        prev = {x, y};
    }
    painter.restore();
}


void DashBoardWidget::updateData() {
    fetchSystemStats();
    cpu_history.pop_front();
    cpu_history.push_back(cpu_usage);

    memory_history.pop_front();
    memory_history.push_back(memory_usage);
    
    qDebug() << "CPU: " << cpu_usage << "Mem: " << memory_usage;

    DashBoardWidget::update();
}




void DashBoardWidget::fetchSystemStats () {
#ifdef Q_OS_WIN
    static bool init = false;
    static PDH_HQUERY cpuQuery;
    static PDH_HCOUNTER cpuCounter;

    PDH_STATUS status;
    // 第一次初始化：打开查询并添加 counter
    if (!init) {
        status = PdhOpenQuery(NULL, 0, &cpuQuery);
        if (status != ERROR_SUCCESS) {
            qWarning() << "PdhOpenQuery failed:" << status;
            return;
        }
        status = PdhAddCounter(cpuQuery,
            L"\\Processor(_Total)\\% Processor Time",
            0, &cpuCounter);
        if (status != ERROR_SUCCESS) {
            qWarning() << "PdhAddCounter failed:" << status;
            return;
        }
        // 先做一次采样，用于初始化内部状态
        PdhCollectQueryData(cpuQuery);
        init = true;
        // 由于第一次采样没有对比，cpuUsage 暂不更新，保持上一次值
    }

    // 等待一段时间后再第二次采样（此调用与上次采样间隔即为 delta）
    status = PdhCollectQueryData(cpuQuery);
    if (status != ERROR_SUCCESS) {
        qWarning() << "PdhCollectQueryData failed:" << status;
        return;
    }

    // 获取格式化后的值
    PDH_FMT_COUNTERVALUE counterVal;
    status = PdhGetFormattedCounterValue(
        cpuCounter, PDH_FMT_DOUBLE, NULL, &counterVal);
    if (status != ERROR_SUCCESS) {
        qWarning() << "PdhGetFormattedCounterValue failed:" << status;
        return;
    }

    cpu_usage = counterVal.doubleValue;  // 现在应该是 0.0–100.0 之间的合理值

    // 内存部分，GlobalMemoryStatusEx 不需要两次采样
    MEMORYSTATUSEX memSt;
    memSt.dwLength = sizeof(memSt);
    if (GlobalMemoryStatusEx(&memSt)) {
        memory_usage = (memSt.ullTotalPhys - memSt.ullAvailPhys)
                   / (double)memSt.ullTotalPhys * 100.0;
    } else {
        qWarning() << "GlobalMemoryStatusEx failed";
    }
#endif
}